package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"oct30-hw/addConfig"
	"sync"
)

var DB *gorm.DB

func Init() {
	var err error
	Once := sync.Once{}
	config := addConfig.Config.Mysql
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		config.User,
		config.Password,
		config.Host,
		config.Port,
		config.Database,
	)
	Once.Do(func() {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		fmt.Println(err)
		panic("数据库连接失败")
	}
	fmt.Println("数据库连接成功")
	err = DB.AutoMigrate(&User{}, &Article{}, &Like{})
	if err != nil {
		fmt.Println(err)
		panic("数据库迁移失败")
	}
	fmt.Println("数据库迁移成功")
}
